import axios from 'axios'
import { showMessage } from './status';
import { ElMessage } from 'element-plus';


axios.defaults.timeout = 15000
// axios.defaults.withCredentials = true;
// axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8";

axios.interceptors.request.use(
  config => {
    return config;
  },
  error => {
    const { response } = error;
        if (response) {
            // 请求已发出，但是不在2xx的范围
            showMessage(response.status);           // 传入响应码，匹配响应码对应信息
            return Promise.reject(response.data);
        } else {
            ElMessage.warning('网络连接异常,请稍后再试!');
        }
  }
);

axios.interceptors.response.use(
  response => {
    if (response.status == 200) {
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  error => {
    console.log("请求异常")
  }
);

export default function request(url='', params={}, type='POST'){
  return new Promise((resolve, reject) => {
      let promise;
      if (type.toUpperCase() == 'GET') {
          promise = axios({url, params})
      } else if (type.toUpperCase() == 'POST') {
          promise = axios({
              method: 'POST',
              url,
              data:params
          })
      }
      promise?.then(res => {
          resolve(res)
      }).catch(err => {
          reject(err)
      })
  })
}


